package com.lzt.admin.common.exception;

import com.lzt.admin.common.result.ResultJson;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class CommonExceptionManager {
    @ExceptionHandler(BindException.class)
    public ResultJson handleException(BindException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        String defaultMessage = allErrors.get(0).getDefaultMessage();
        return ResultJson.fail(defaultMessage);
    }
    @ExceptionHandler(DuplicateKeyException.class)
    public ResultJson handleException(DuplicateKeyException ex) {
        return ResultJson.fail("输入的内容重复，请确认单据是否存在重复信息");
    }


    @ExceptionHandler(Exception.class)
    public ResultJson handleException(Exception ex) {
        return ResultJson.fail(ex.getMessage());
    }
}
